<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import CustomNavbar from './components/CustomNavbar.vue'
import { provide, ref } from 'vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import type { XtxGuessInstance } from '@/types/components'
import PageSkeleton from './components/PageSkeleton.vue'
import { useGuessList } from '@/composables'

const bannerlist = ref<BannerItem[]>([])
// 获取轮播图数据
const getBannerList = async () => {
  const res = await getHomeBannerAPI()
  bannerlist.value = res.result
}

const categorylist = ref<CategoryItem[]>([])
//获取前台分类数据
const getCategoryList = async () => {
  const res = await getHomeCategoryAPI()
  categorylist.value = res.result
}

//获取热门推荐数据
const hotlist = ref<HotItem[]>([])
const getHotList = async () => {
  const res = await getHomeHotAPI()
  hotlist.value = res.result
}
//猜你喜欢组合式 函数
const { guessRef, onScrolltolower } = useGuessList()

// 下拉刷新状态
const isTriggered = ref(false)

// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 重置猜你喜欢组件数据
  guessRef.value?.resetData() // 加载数据
  await Promise.all([getBannerList(), getCategoryList(), getHotList()]) // 关闭动画
  isTriggered.value = false
}
const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getBannerList(), getCategoryList(), getHotList()])
  isLoading.value = false
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <scroll-view
    scroll-y
    class="scroll-view"
    refresher-enabled
    @scrolltolower="onScrolltolower"
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
  >
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerlist" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categorylist" />
      <!-- 热门面板 -->
      <HotPanel :list="hotlist" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>

  <!-- 首页内容 -->
</template>

<style lang="scss">
//
page {
  background-color: #f7f7f7f7;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.scroll-view {
  flex: 1;
}
</style>
